package socketTransmission;

import java.net.*;
import java.util.List;
import java.util.Random;
import java.io.*;

/**
 * this program implements the client side of sending object to server
 * 
 * @author Ganggao Zhu
 * @version 1.0 2011/10/19
 * 
 */

public class Client implements Runnable {

	
	private SocketConnectionPool conncetionPool;
	private Message message;
//	private List<Message> objectList;
	private int tag;
	
	Client(SocketConnectionPool connectionPool,int tag){
		this.conncetionPool = connectionPool;
		this.tag = tag;
	}
	
	public void testProduceAndConsum(){
		
		Random randomGenerator = new Random();
		try {
			Thread.sleep(randomGenerator.nextInt(1000));
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String temp = this.conncetionPool.get();
		System.out.println("ClientThread "+tag+">"+temp);
		
		try {
			Thread.sleep(randomGenerator.nextInt(1000));
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		conncetionPool.put(temp);
		
		try {
			Thread.sleep(randomGenerator.nextInt(1000));
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		
		
		
			message = new Message("Hello from Client "+tag);
			
			Socket client = this.conncetionPool.getSocket();
			
			SocketConnection socketConnection =this.conncetionPool.getConnection(client);
			
			socketConnection.sendMessage(message);
			
			message = socketConnection.receiveMessage();
			
			System.out.println("Client "+ Thread.currentThread().getName()+" > "+ message.message);
			
			conncetionPool.returnSocket(client);
			
		
	}


}
